﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TodayWhoModel;
using System.Web.Services;

namespace TodayWho
{
    public partial class login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //Page.Form.DefaultButton = btnLogin.UniqueID;
        }

        protected void btnLogin_OnClick(object sender, EventArgs e)
        {
            UserModel user = new UserModel();
            user.Email = txtEmail.Text.Trim();
            user.Password = txtPassword.Text.Trim();

            if (user.CheckLogin())
            {
                Session.Add("userId", user.UserId);
                Session.Add("email", user.Email);
                Session.Add("userName", user.UserName);
                Session.Add("categoryId", user.CategoryId);
                Response.Redirect("profile.aspx?u="+user.UserName);
            }
            else
            {
                lblLoginErrors.Text = "Email adresini ya da şifrenizi yanlış girdiniz..";
                lblLoginErrors.Visible = true;
            }
        }

        [WebMethod (EnableSession=true)]
        public static string FbLogin(string fbUserId, string token, string email, string name)
        {
            string res = "0";
            UserModel user = new UserModel();
            user.Email = email;
            user.NameSurname = name;
            user.FbUserId = fbUserId;
            user.FbToken = token;

            if (user.IsEmailUnique())
            {
                user.InsertFbNew();
            }
            else
            {
                user.InsertFbExisting();   
            }
            user.CheckFblogin();
            HttpContext.Current.Session.Add("userId", user.UserId);
            HttpContext.Current.Session.Add("email", user.Email);
            HttpContext.Current.Session.Add("userName", user.UserName);
            HttpContext.Current.Session.Add("categoryId", user.CategoryId);
            HttpContext.Current.Session.Add("fbIsComplete", user.FbIsComplete);
            if (user.FbIsComplete)
            {
                
               res = "profile.aspx?u=" + user.UserName;
            }
            else
            {
                res = "fbregister.aspx";
            }

            return res;
        }
    }
}